<template>
  <div style="margin-left:15px;">
    <el-form ref="form" :model="articleForm" :rules="rules" style="margin-top: 15px;" size="small" label-width="100px">
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="articleForm.title" style="width: 646px" placeholder="请输入公告标题，不能为空" />
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-switch
          v-model="articleForm.isTop"
          active-color="#409EFF"
          inactive-color="#F56C6C"
        />
      </el-form-item>
      <el-form-item label="推送全体用户" prop="push">
        <el-switch
          v-model="articleForm.push"
          active-color="#409EFF"
          inactive-color="#F56C6C"
        />
      </el-form-item>
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-upload"
        @click="crud.toAdd"
      >
        添加附件
      </el-button>
      <div v-if="fileLists && fileLists.length > 0" style="height:70px;margin-top: 20px;display: flex;flex-direction: row; align-items: flex-start;flex-wrap: wrap;">
        <template v-for="file in fileLists">
          <div :key="file.id" style="margin-left: 20px;display: flex; flex-direction: column; align-items: center;">
            <el-image
              v-if="file.type==='图片'"
              style="width: 100px;height: 50px;"
              :src="baseApi + '/file/' + file.type + '/' + file.realName"
              :preview-src-list="[baseApi + '/file/' + file.type + '/' + file.realName]"
            />
            <video v-if="file.type==='视频'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 100px;height: 50px;" />
            <audio v-if="file.type==='音乐'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 250px;height: 50px;" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') > 0" style="width: 100px;height: 50px;" icon-class="pdf" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') < 0" style="width: 100px;height: 50px;" icon-class="attachmentdoc" />
            <span style="max-width: 10em;margin-top:15px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"><a
              class="el-link--primary"
              style="color: #1890ff;"
              target="_blank"
              @click="deleteFile(file)"
            >
              <i class="el-icon-delete" style="width: 20px;height: 20px;" />
            </a>{{ file.name }}</span>
          </div>
        </template>
      </div>
      <div ref="editor" class="editor" />
      <el-button
        :loading="loading"
        style="margin-left:1.6%;margin-bottom: 30px"
        size="medium"
        type="primary"
        @click="doSubmit"
      >保存公告
      </el-button>
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.add ? '文件上传' : '编辑文件'" width="500px">
        <el-form ref="form" :model="form" size="small" label-width="80px">
          <el-form-item label="文件名">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <!--   上传文件   -->
          <el-form-item v-if="crud.status.add" label="上传">
            <el-upload
              ref="upload"
              :limit="1"
              :before-upload="beforeUpload"
              accept="audio/*, image/*,video/*,.doc,.pdf,.docx"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-change="handleChange"
              :action="fileUploadApi + '?name=' + form.name"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传图片,视频,音频,pdf,word文档，且不超过500M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="loading" type="primary" @click="upload">确认</el-button>
        </div>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>
import { add, edit, getNotice } from '@/api/system/notice'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { upload } from '@/utils/upload'
import crudFile from '@/api/tools/localStorage'
import { mapGetters } from 'vuex'
import E from 'wangeditor'
const defaultForm = { id: null, name: '' }
export default {
  name: 'NoticeDetail',
  cruds() {
    return CRUD({ title: '文件', queryOnPresenterCreated: false, url: 'api/localStorage', crudMethod: { ...crudFile }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      loading: false,
      articleForm: { title: '', content: '', enabled: 'true', isTop: false, push: true },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
      headers: { 'Authorization': getToken() },
      fileLists: []
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi',
      'fileUploadApi'
    ])
  },
  mounted() {
    const _this = this
    this.crud.optShow.add = false
    var editor = new E(this.$refs.editor)
    // 自定义菜单配置
    editor.config.zIndex = 10
    // 文件上传
    editor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
      files.forEach(image => {
        upload(_this.imagesUploadApi, image).then(res => {
          const data = res.data
          const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
          insert(url)
        })
      })
    }
    editor.config.excludeMenus = ['video', 'code']
    editor.config.onchange = (html) => {
      this.articleForm.content = html
    }
    editor.create()
    if (this.$route.query.id) {
      getNotice(this.$route.query.id).then(res => {
        res.enabled = res.enabled ? 'true' : 'false'
        this.articleForm = res
        this.fileLists = res.attachments || []
        editor.txt.html(this.articleForm.content)
      })
    }
  },
  methods: {

    handleChange(file, fileList) {
      this.form.name = file.name
    },
    deleteFile(file) {
      this.$confirm(`确认删除${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('删除file', file)
        this.crud.doDelete([file])
        this.fileLists.splice(this.fileLists.indexOf(file), 1)
      }).catch(() => {
      })
    },
    upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 500
      if (!isLt2M) {
        this.loading = false
        this.form.name = ''
        this.$message.error('上传文件大小不能超过 500MB!')
      }
      console.log(file)
      if (this.fileLists.find(v => v.type === '视频') && file.type.indexOf('video') >= 0) {
        this.loading = false
        this.form.name = ''
        this.$message.error('已经存在一个视频附件!')
        isLt2M = false
      }
      if (this.fileLists.find(v => v.type === '音乐') && file.type.indexOf('audio') >= 0) {
        this.loading = false
        this.form.name = ''
        this.$message.error('已经存在一个音频附件!')
        isLt2M = false
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      this.fileLists.push(response)
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.fileLists) {
            this.articleForm.attachmentIds = this.fileLists.map(v => `${v.id}`).join(';')
          }
          const execute = this.articleForm.id ? edit : add
          execute(this.articleForm).then(res => {
            this.$notify({
              title: '保存成功',
              type: 'success',
              duration: 2500
            })
            this.loading = false
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.back()
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    }

  }
}
</script>

<style scoped>
.editor {
  text-align: left;
  margin: 20px;
  width: 730px;
}
.filter-item {
  margin-left: 20px;
}
::v-deep .w-e-text-container {
  height: 360px !important;
}
</style>
